/********************************************************************
        File :			IOCPQueue.cpp
        Creation date :	2010/6/27
		
        License :			Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com

                                   Licensed under the Apache License, Version 2.0 (the "License");
                                   you may not use this file except in compliance with the License.
                                   You may obtain a copy of the License at
				
                                           http://www.apache.org/licenses/LICENSE-2.0
				
                                   Unless required by applicable law or agreed to in writing, software
                                   distributed under the License is distributed on an "AS IS" BASIS,
                                   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                   See the License for the specific language governing permissions and
                                   limitations under the License.
	
	
 *********************************************************************/
#include "StdAfx.h"
#include "IOCPQueue.h"

namespace PushFramework {

    IOCPQueue::IOCPQueue(void) {
    }

    IOCPQueue::~IOCPQueue(void) {
    }

    bool IOCPQueue::Create() {

        int pollsize = 1;
        pollQueue = epoll_create(pollsize);
        if (pollQueue < 0) {
            cout << "unable to create pollQueue" << endl;
            return false;
        }
        return true;
    }

    void IOCPQueue::Free() {
        close(pollQueue);
    }

    void IOCPQueue::PostTerminationSignal() {
        //Nothing..
    }

    int IOCPQueue::GetQueuedEvent(epoll_event *pEvents, int nMaxEvents) {
        while (true) {
            int rval = epoll_wait(pollQueue, pEvents, nMaxEvents, 1000);

            if (rval == 0) {
                //cout << "timeout happened" << endl;
                return rval;
            }

            if (rval < 0) {
                if (errno == EAGAIN) {
                    continue;
                }
                perror("Error on epoll_wait");
                return rval;
                // if(errno != EINTR)
            }

            return rval;
        }
    }

    bool IOCPQueue::AddSocketContext(SOCKET clientSocket, void* lpObject) {
        cout << "Adding new socket to pollQueue" << endl;
        epoll_event ev;


        ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
        ev.data.ptr = lpObject;
        ev.data.fd = clientSocket;

        if (epoll_ctl(pollQueue, EPOLL_CTL_ADD, clientSocket, &ev) < 0) {

            cout << "Unable to add client socket" << endl;
        }

        return true;
    }
}

